/**
 * 
 */
package org.jeecg.modules.bj.util;


import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;


import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author fenghaiyun 2012-7-3
 */
public class PoiUtil {

	/** 模板目录 */
	private static final String DIR_MODEL = "report/";

    /*public static File expExcel(String modFileName, List data, Map<String, String> head,
        List<List<Map<String, Object>>> otherData)
    {
	    File file = null;
        try {
            Struts2Utils.renderExcel(expExcelPage(modFileName, data, head, otherData, null), modFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
	}*/
	
	/**
	 * 用于报表的导出
	 * 
	 * @param modFileName
	 *            模版文件名称
	 * @param data
	 *            数据Bean集合
	 * @return 生成的文件
	 */
	/*public static File expExcel(String modFileName, List data, Map<String, String> head) {
        return expExcel(modFileName, data, head, null);
	}*/

	/**
	 * 用于报表的导出
	 *
	 * @param modFileName
	 *            模版文件名称
	 * @param data
	 *            数据Bean集合（产生多行）
	 * @param data2
	 *            数据Bean集合（不产生多行，只填充对应的cell）
	 * @return 生成的文件
	 */
	/*public static File expExcel2(String modFileName, List data, Map<String, String> head, Map<Integer[], Object> map) {
		File file = null;
		try {
			Struts2Utils.renderExcel(expExcelPage2(modFileName, data, head, map), modFileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}*/

    /**
     * 
     * @param modFileName
     * @param data
     * @param head
     * @param afterMainData 在主体数据渲染后，接着渲染其他数据
     * @param otherCellRecord 崽整个excel模板中，可能会有其他设置的零星的参数化单元格
     * @return 生成的临时文件
     * @throws Exception
     */
   /* public static File expExcelPage(String modFileName, List data, Map<String, String> head,
        List<List<Map<String, Object>>> afterMainData, Map<String, String> otherCellRecord)
            throws Exception
    {
        File file = null;
        
        InputStream inp = new FileInputStream(getTmpModelFile(DIR_MODEL + modFileName));
        if (!inp.markSupported()) {
            inp = new PushbackInputStream(inp, 8);
        }
        if (POIFSFileSystem.hasPOIFSHeader(inp)) {// excel97-2003没考虑数据量问题
            HxlsWriteAbstract hxls = new HxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
            file = hxls.exportData(data, head, afterMainData, otherCellRecord);
        } else if (POIXMLDocument.hasOOXMLHeader(inp)) {
            XxlsWriteAbstract xxls = new XxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
            file = xxls.exportData(data, head, afterMainData, otherCellRecord);
        } else {
            throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
        }
        inp.close();
        
        return file;
	}*/
	
	/*public static File expExcelPage(String modFileName, List data, Map<String, String> head) throws Exception{
        return expExcelPage(modFileName, data, head, null, null);
		
	}*/

	/**
	 *
	 * @param modFileName
	 * @param data(产生若干记录)
	 * @param head
	 * @param map(不产生若干记录，只填充对应的cell)
	 * @return 生成的临时文件
	 * @throws Exception
	 */
	/*public static File expExcelPage2(String modFileName, List data, Map<String, String> head, Map<Integer[], Object> map) throws Exception {
		File file = null;

		InputStream inp = new FileInputStream(getTmpModelFile(DIR_MODEL + modFileName));
		if (!inp.markSupported()) {
			inp = new PushbackInputStream(inp, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(inp)) {// excel97-2003没考虑数据量问题
			HxlsWriteAbstract hxls = new HxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
			file = hxls.exportData2(data, head, map);
		} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
			XxlsWriteAbstract xxls = new XxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
//			file = xxls.exportData(data, head, map);
		} else {
			throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
		}
		inp.close();

		return file;
	}*/

	/*public static FileTransfer expExcelPageDwr(String modFileName, List data, Map<String, String> head) {
		FileTransfer file = null;
		try {
			InputStream in = new FileInputStream(expExcelPage(modFileName, data, head));
	        file = new FileTransfer(modFileName,"application/vnd.ms-excel",in);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}*/


	/**
	 * 用于报表的导入
	 * 
	 * @param <X>
	 * @param modFileName
	 *            模版文件名称
	 * @param file
	 *            导入的excel文件
	 * @param xClazz
	 *            转换的javabean Class
	 * @return
	 */
	/*public static <X> List<X> impExcel(String modFileName, File file, Class<?> xClazz) {
		try {
			WBook xls = null;
			InputStream inp = new FileInputStream(file);
			if (!inp.markSupported()) {
				inp = new PushbackInputStream(inp, 8);
			}
			if (POIFSFileSystem.hasPOIFSHeader(inp)) {
				xls = new HxlsBook(file, getTmpModelFile(DIR_MODEL + modFileName), xClazz);
			} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
				xls = new XxlsBook(file, getTmpModelFile(DIR_MODEL + modFileName), xClazz);
			} else {
				throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
			}
			inp.close();
			xls.process();
			return xls.getFxs();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}*/

/*	public static File expWord(String modFileName, List data, Map<String, String> head, Map<Integer[], Object> map) {
		File file = null;
		try {
			Struts2Utils.renderWord(expWordPage(modFileName, data, head, map), modFileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}*/

/*	*//**
	 *
	 * @param modFileName
	 * @param data(产生若干记录)
	 * @param head
	 * @param map(不产生若干记录，只填充对应的cell)
	 * @return 生成的临时文件
	 * @throws Exception
	 *//*
	public static File expWordPage(String modFileName, List data, Map<String, String> head, Map<Integer[], Object> map) throws Exception {
		File file = null;

		InputStream inp = new FileInputStream(getTmpModelFile(DIR_MODEL + modFileName));
		if (!inp.markSupported()) {
			inp = new PushbackInputStream(inp, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(inp)) {// excel97-2003没考虑数据量问题
			HxlsWriteAbstract hxls = new HxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
			file = hxls.exportData2(data, head, map);
		} else if (POIXMLDocument.hasOOXMLHeader(inp)) {
			XxlsWriteAbstract xxls = new XxlsWriteAbstract(getTmpModelFile(DIR_MODEL + modFileName));
//			file = xxls.exportData(data, head, map);
		} else {
			throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
		}
		inp.close();

		return file;
	}*/

	/**
	 * 创建模板临时文件
	 * 
	 * @param modelName
	 * @return
	 */
	public static File getTmpModelFile(String modelName) {
		try {
			String suffix = modelName.substring(modelName.lastIndexOf("."));
			File tmp_f = File.createTempFile("model_tmp", suffix);
			InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(modelName);
			FileOutputStream out = new FileOutputStream(tmp_f);
			byte[] chunk = new byte[1024];
			int count;
			while ((count = inStream.read(chunk)) >= 0) {
				out.write(chunk, 0, count);
			}
			out.flush();
			return tmp_f;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] s) throws Exception {
		File modelFile = getTmpModelFile("asm-license.txt");
		System.out.println(modelFile);
	}
	/**
     * 获取图片格式
     *
     * @param imgFile
     * @return
     */
    public static int getPictureFormat(String imgFile) {
        int format;
        if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
        else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
        else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
        else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
        else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
        else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
        else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
        else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
        else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
        else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
        else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
        else {
            System.err.println("Unsupported picture: " + imgFile +
                    ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
            System.err.println("不支持的图片格式: " + imgFile +
                    ". 仅支持 emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg 格式的图片");
            format = -1;
        }
        return format;
    }
    
    
    /** poi列头单元格样式
     * 
     * @param workbook
     * @return
     */
   
    /*public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook, HSSFCellStyle style) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)14);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("黑体");
        //设置样式;
        //设置背景颜色;
//        style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
        //solid 填充  foreground  前景色
//        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(true);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

    *//**poi导出 单元格设置边框字体
     * 
     * @param
     * @return
     *//*
    
    public HSSFCellStyle getStyle(HSSFWorkbook workbook, HSSFCellStyle style) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)12);
        //字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("宋体");
        //设置样式;
        //设置背景颜色;
     //  style.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);
        //solid 填充  foreground  前景色
      //  style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        //设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        //设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        //设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        //设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }*/
    
    
 
	//表头
	public static XSSFCellStyle setXSSFCellStyleHeader(SXSSFWorkbook sxssfWorkbook) {
		XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
		Font font = sxssfWorkbook.createFont();
			// 字体大小
			font.setFontHeightInPoints((short) 12);
			font.setFontName("宋体");
			// 将字体应用到样式上面
			xssfCellStyle.setFont(font);

			//设置填充方案
			xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			//设置自定义填充颜色
			xssfCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
			setBorder(xssfCellStyle);
		return xssfCellStyle;
	}
	/**
	 * 自定义样式
	 * @param sxssfWorkbook
	 * @param horizontalAlignment	水平
	 * @param verticalAlignment	垂直
	 * @param borderBottom	下边框
	 * @param borderLeft	左边框
	 * @param borderTop 	上边框
	 * @param borderRight 右边框
	 * @param WrapText 是否合并
	 * @return
	 */
	public static XSSFCellStyle customXSSFCellStyleHeader(
			SXSSFWorkbook sxssfWorkbook,
			HorizontalAlignment horizontalAlignment,
			VerticalAlignment verticalAlignment,
			BorderStyle borderBottom,
			BorderStyle borderLeft,
			BorderStyle borderTop,
			BorderStyle borderRight,
			Boolean WrapText 
			) {
		XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
		Font font = sxssfWorkbook.createFont();
			// 字体大小
			font.setFontHeightInPoints((short) 12);
			font.setFontName("宋体");
			// 将字体应用到样式上面
			xssfCellStyle.setFont(font);

			//设置填充方案
//			xssfCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			//设置自定义填充颜色
//			xssfCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
			// 水平居中
			xssfCellStyle.setAlignment(horizontalAlignment);
			// 垂直居中
			xssfCellStyle.setVerticalAlignment(verticalAlignment);
			//下边框
			xssfCellStyle.setBorderBottom(borderBottom);
			//左边框
			xssfCellStyle.setBorderLeft(borderLeft);
			//上边框
			xssfCellStyle.setBorderTop(borderTop);
			//右边框
			xssfCellStyle.setBorderRight(borderRight);
			//自动换行
			//xssfCellStyle.setWrapText(WrapText);
		return xssfCellStyle;
	}
	//数据行
	public static XSSFCellStyle setXSSFCellStyleRow(SXSSFWorkbook sxssfWorkbook,short typeface) {
		XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
		Font font = sxssfWorkbook.createFont();
			// 字体大小
			font.setFontHeightInPoints(typeface);
			font.setFontName("宋体");
			// 将字体应用到样式上面
			xssfCellStyle.setFont(font);
			setBorder(xssfCellStyle);

		return xssfCellStyle;
	}
	public static XSSFCellStyle setBorder(XSSFCellStyle xssfCellStyle) {
		// 水平居中
		xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
		// 垂直居中
		xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		//下边框
		xssfCellStyle.setBorderBottom(BorderStyle.THIN);
		//左边框
		xssfCellStyle.setBorderLeft(BorderStyle.THIN);
		//上边框
		xssfCellStyle.setBorderTop(BorderStyle.THIN);
		//右边框
		xssfCellStyle.setBorderRight(BorderStyle.THIN);
		//自动换行
		xssfCellStyle.setWrapText(true);

		return xssfCellStyle;
	}

	//下载
	public static void writeExcel(String filename, Workbook workbook, HttpServletResponse response) throws Exception {
		OutputStream ouputStream = null;
		try {
			filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setHeader("Content-disposition", "attachment;filename=" + filename);
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != ouputStream) {
				ouputStream.close();
			}
		}
	}

}
